import 'dart:io';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:fucius/Models/JobModel.dart';
import 'package:fucius/utils/pull_push.dart';

import 'jobDetail.dart';

class JobPage extends StatefulWidget {
  @override
  _JobPageState createState() => _JobPageState();
}

class _JobPageState extends State<JobPage> with TickerProviderStateMixin {
  List<JobModel> _jobs = [];
  var items = List<JobModel>();
  ScrollController controller = new ScrollController();

  ScrollPhysics scrollPhysics = new RefreshAlwaysScrollPhysics();

  var httpClient = new HttpClient();
  var url = "";
  var _result = "";
  String customRefreshBoxIconPath = "assets/images/icon_arrow.png";
  AnimationController customBoxWaitAnimation;
  int rotationAngle = 0;
  String customHeaderTipText = "refresh";
  String defaultRefreshBoxTipText = "refresh";

  // 下拉刷新
  TriggerPullController triggerPullController = new TriggerPullController();

  TextEditingController editingController = TextEditingController();


  Future<dynamic> getJob() async{
    await Firestore.instance.collection('job').getDocuments().then((QuerySnapshot data){
      print(data);

      setState(() {
        data.documents.forEach((v) =>
            _jobs.add(JobModel(job_title: v["Job Title"], department: v['Department'],
            collage: v["Collage"], university: v["University"], topic: v["Topic/Class/Title"], audenice: v["Audenice"], contacts: v["Contacts"], expect_time: v['Expect Time']))

        );
        items.addAll(_jobs);
      });
    }).catchError((error) {
      print(error);
      return null;
    });
  }

  void filterSearchResults(String query) {
    List<JobModel> dummySearchList = List<JobModel>();
    dummySearchList.addAll(_jobs);
    if(query.isNotEmpty) {
      List<JobModel> dummyListData = List<JobModel>();
      dummySearchList.forEach((item) {
        if(item.job_title.contains(query)) {
          dummyListData.add(item);
        }
      });
      setState(() {
        items.clear();
        items.addAll(dummyListData);
      });
      return;
    } else {
      setState(() {
        items.clear();
        items.addAll(_jobs);
      });
    }
  }


  @override
  void initState() {
    super.initState();
    customBoxWaitAnimation = new AnimationController(
        duration: const Duration(milliseconds: 1000 * 100), vsync: this);
    getJob();

  }

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      backgroundColor: Colors.white,
      appBar: AppBar(
      backgroundColor: Colors.blue,
//        elevation: 4,
      leading: IconButton(
        icon: Icon(
          Icons.keyboard_backspace,
          color: Colors.black,
        ),
        onPressed: (){},
      ),
      title: TextField(
        onChanged: (value) {
          filterSearchResults(value);
        },
        controller: editingController,
        decoration: InputDecoration(
            labelText: "Search",
            hintText: "Search",
            prefixIcon: Icon(Icons.search),
        ),
      ),
    ),
      body: Container(
        child: PullAndPush(
                //如果你headerRefreshBox和footerRefreshBox全都自定义了，则default**系列的属性均无效，
                //假如有一个RefreshBox是用默认的（在该RefreshBox Enable的情况下）则default**系列的属性均有效
                defaultRefreshBoxTipText: defaultRefreshBoxTipText,
                headerRefreshBox: _getCustomHeaderBox(),
                triggerPullController: triggerPullController,

                //你也可以自定义底部的刷新栏；you can customize the bottom refresh box
                animationStateChangedCallback: (AnimationStates animationStates,
                    RefreshBoxDirectionStatus refreshBoxDirectionStatus) {
                  _handleStateCallback(animationStates, refreshBoxDirectionStatus);
                },
                listView: new ListView.builder(
                    itemCount: items.length,
                    itemBuilder: (context, index) {
                      return buildJobItem(context, index);
                    }),

                loadData: (isPullDown) async {
                  await _loadData(isPullDown);
                },
                scrollPhysicsChanged: (ScrollPhysics physics) {
                  //这个不用改，照抄即可；This does not need to change，only copy it
                  setState(() {
                    scrollPhysics = physics;
                  });
                },
              ),


        ),
      );
  }

  buildJobItem(BuildContext context, int index) {
    JobModel job = items[index];

    var jobItem = InkWell(
        onTap: () => navJobDetail(job, index), child: JobListItem(job: job));
    return jobItem;
  }

  Future _loadData(bool isPullDown) async {
  }

  Widget _getCustomHeaderBox() {
    return new Container(
        color: Color.fromARGB(255, 0, 215, 198), //Colors.grey,
        child: new Row(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            new Align(
              alignment: Alignment.centerLeft,
              child: new RotatedBox(
                quarterTurns: rotationAngle,
                child: new RotationTransition(
                  //布局中加载时动画的weight
                  child: new Image.asset(
                    customRefreshBoxIconPath,
                    height: 45.0,
                    width: 45.0,
                    fit: BoxFit.cover,
                  ),
                  turns: new Tween(begin: 100.0, end: 0.0)
                      .animate(customBoxWaitAnimation)
                        ..addStatusListener((animationStatus) {
                          if (animationStatus == AnimationStatus.completed) {
                            customBoxWaitAnimation.repeat();
                          }
                        }),
                ),
              ),
            ),
            new Align(
              alignment: Alignment.centerRight,
              child: new ClipRect(
                child: new Text(
                  customHeaderTipText,
                  style:
                      new TextStyle(fontSize: 18.0, color: Color(0xffe6e6e6)),
                ),
              ),
            ),
          ],
        ));
  }

  void _handleStateCallback(AnimationStates animationStates,
      RefreshBoxDirectionStatus refreshBoxDirectionStatus) {
    switch (animationStates) {
      //RefreshBox高度达到50,上下拉刷新可用;RefreshBox height reached 50，the function of load data is  available
      case AnimationStates.DragAndRefreshEnabled:
        setState(() {
          //3.141592653589793是弧度，角度为180度,旋转180度；3.141592653589793 is radians，angle is 180⁰，Rotate 180⁰
          rotationAngle = 2;
        });
        break;

      //开始加载数据时；When loading data starts
      case AnimationStates.StartLoadData:
        setState(() {
          customRefreshBoxIconPath = "assets/images/refresh.png";
          customHeaderTipText = "fresh.....";
        });
        customBoxWaitAnimation.forward();
        break;

      //加载完数据时；RefreshBox会留在屏幕2秒，并不马上消失，这里可以提示用户加载成功或者失败
      case AnimationStates.LoadDataEnd:
        customBoxWaitAnimation.reset();
        setState(() {
          rotationAngle = 0;
          if (refreshBoxDirectionStatus == RefreshBoxDirectionStatus.PULL) {
//            customRefreshBoxIconPath = "assets/images/icon_cry.png";
            customHeaderTipText = "Refresh";
          } else if (refreshBoxDirectionStatus ==
              RefreshBoxDirectionStatus.PUSH) {
            defaultRefreshBoxTipText = "Refresh";
          }
        });
        break;

      //RefreshBox已经消失，并且闲置；RefreshBox has disappeared and is idle
      case AnimationStates.RefreshBoxIdle:
        setState(() {
          rotationAngle = 0;
          defaultRefreshBoxTipText = customHeaderTipText = "Refresh";
//          customRefreshBoxIconPath = "assets/images/icon_arrow.png";
        });
        break;
    }
  }

  navJobDetail(JobModel job, int index) {
    Navigator.of(context).push(new PageRouteBuilder(
        opaque: false,
        pageBuilder: (BuildContext context, _, __) {
          return JobDetail(job);
        },
        transitionsBuilder: (_, Animation<double> animation, __, Widget child) {
          return new FadeTransition(
              opacity: animation,
              child: new SlideTransition(
                position: new Tween<Offset>(
                  begin: const Offset(0.0, 1.0),
                  end: Offset.zero,
                ).animate(animation),
                child: child,
              ));
        }));
  }
}

class JobListItem extends StatelessWidget {
  JobListItem({this.job});

  final JobModel job;

  @override
  Widget build(BuildContext context) {
    return new Padding(
      padding: const EdgeInsets.only(
        top: 3.0,
        left: 5.0,
        right: 5.0,
        bottom: 3.0,
      ),
      child: new SizedBox(
        child: new Card(
          elevation: 0.0,
          child: new Row(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              new Expanded(
                child: new Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  mainAxisSize: MainAxisSize.min,
                  children: <Widget>[
                    new Row(
                      children: <Widget>[
                        new Padding(
                          padding: const EdgeInsets.only(
                            top: 10.0,
                            left: 10.0,
                            bottom: 5.0,
                          ),
                          child: Container(
                            width: 370,
                            child: Text(
                              job.job_title,
                              softWrap: true,
                              textAlign: TextAlign.left,
                              overflow: TextOverflow.ellipsis,
                              maxLines: 1,
                              style: TextStyle(
                                fontSize: 15,
                              ),
                            ),
                          ),
                        ),
                      ],
                    ),
                    new Container(
                      child: new Text(
                        job.university,
                        textAlign: TextAlign.left,
                        style: new TextStyle(fontSize: 13.0, color: Colors.grey),
                      ),
                      margin: const EdgeInsets.only(
                          top: 5.0, left: 10.0, bottom: 5.0),
                    ),
                    new Container(
                      child: new Text(
                        job.topic,
                        textAlign: TextAlign.left,
                        style: new TextStyle(fontSize: 13.0, color: Colors.grey),
                      ),
                      margin: const EdgeInsets.only(
                          top: 5.0, left: 10.0, bottom: 5.0),
                    ),
                    new Row(
                      children: <Widget>[
                        new Padding(
                          padding: const EdgeInsets.only(
                            top: 5.0,
                            left: 10.0,
                            right: 5.0,
                            bottom: 5.0,
                          ),
                          child: new Text("Job phone: " + job.contacts,
                              style: new TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.grey)),
                        ),
                      ],
                    ),
                    new Row(
                      children: <Widget>[
                        new Padding(
                          padding: const EdgeInsets.only(
                            left: 10.0,
                            right: 5.0,
                            bottom: 15.0,
                          ),
                          child: new Text("Posting Date: " + job.expect_time,
                              style: new TextStyle(
                                  fontSize: 12.0,
                                  color: Colors.grey)),
                        ),
                      ],
                    ),
                    new Divider(),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
